/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-12 18:19:45
 */
import { useUserInfoStore } from '@/stores/userInfo'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const mockInstance = axios.create({
  baseURL: '/mock',
  timeout: 5000,
})

// 添加请求拦截器
mockInstance.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
mockInstance.interceptors.response.use(
  (response) => {
    // 简化响应数据
    const res = response.data
    return res
  },
  (error) => {
    ElMessage({
      type: 'error',
      message: error.message || '网络异常',
      duration: 5000,
    })
    return Promise.reject(error)
  },
)

export interface IReqDataRes<T> {
  code: number
  data: T
  message: string
  success: boolean
}

/**
 * @description: 二次封装axios请求
 * @return {*}
 * @param {*} T
 */
const http = <T>(url: string, method: Method, data?: unknown) => {
  const newMeThod = method.toLocaleUpperCase()
  return mockInstance.request<IReqDataRes<T>, IReqDataRes<T>>({
    url,
    method: newMeThod,
    params: newMeThod === 'GET' ? data : {},
    data:
      newMeThod === 'POST' || newMeThod === 'PUT' || newMeThod === 'DELETE'
        ? data
        : {},
  })
}

export { mockInstance, http }
